import { type AfterFetchContext, objectPick } from '@vueuse/core'
import type { IPorject, ProjectTableNeeds } from '~/types/apis/project'
import type { IEnvironment, EnvironmentTableNeeds } from '~/types/apis/environment'
import type { IDatabase, DatabaseTableNeeds } from '~/types/apis/database_msg'
import type { IProxy, ProxyTableNeeds } from '~/types/apis/proxy'
import type { IBasic, StepItem } from '~/types/apis/basic'

export const useGlobalConfigStore = defineStore(
  'global-config',
  () => {
    const config = reactive<{
      projectId: number
      projectDatas: IPorject[]
      projectListDataProxy: ProjectTableNeeds[]
      environmentId: number | null
      environmentDatas: IEnvironment[]
      environmentListDataProxy: EnvironmentTableNeeds[]
      databaseId:number
      proxyId:number
      databaseDatas: IDatabase[]
      databaseListDataProxy: DatabaseTableNeeds[]
      proxyDatas: IProxy[]
      proxyListDataProxy: ProxyTableNeeds[]
    }>({
      projectId: 1,
      projectDatas: [],
      projectListDataProxy: [],
      environmentId: 1,
      environmentDatas: [],
      environmentListDataProxy: [],
      databaseId:1,
      proxyId: 1,
      databaseDatas: [],
      databaseListDataProxy: [],
      proxyDatas:[],
      proxyListDataProxy:[]
    })

    const loginToken = ref('')

    const isLogin = computed(() => !!loginToken.value)

    function setLoginToken(token: string) {
      loginToken.value = token
    }

    /**
     * 获取项目project信息
     */
    const {
      isFetching: loadingWithGetProjectDatas,
      execute: fetchGetProjectDatas,
    } = useCustomFetch<IPorject[]>('/engine-service/api/v1/project/list', {
      initialData: [],
      immediate: false,
      afterFetch(ctx: AfterFetchContext<IBasic<IPorject[]>>) {
        if (ctx.data && ctx.data.code === 0) {
          config.projectDatas = ctx.data.data
          config.projectListDataProxy = ctx.data.data.map((item) =>
            objectPick(item, ['id', 'name', 'description', 'projectAdmin', 'notificationDTO', 'notificationId']),
          )
          modifyConfig({ projectId: ctx.data.data[0].id })

          return {
            data: ctx.data.data,
            response: ctx.response,
          }
        }
        return {
          data: [],
          response: ctx.response,
        }
      },
    })


    /**
     * 获取环境environment信息
     */
    const {
      isFetching: loadingWithGetEnvironmentDatas,
      execute: fetchGetEnvironmentDatas,
    } = useCustomFetch<IEnvironment[]>('/engine-service/api/v1/env/list', {
      initialData: [],
      immediate: false,
      afterFetch(ctx: AfterFetchContext<IBasic<IEnvironment[]>>) {
        if (ctx.data && ctx.data.code === 0) {
          config.environmentDatas = ctx.data.data
          config.environmentListDataProxy = ctx.data.data.map((item) =>
            objectPick(item, ['id', 'name', 'description', 'projectId', 'port', 'domain', 'protocol']),
          )
          modifyConfig({ environmentId: ctx.data.data[0].id })

          return {
            data: ctx.data.data,
            response: ctx.response,
          }
        }
        return {
          data: [],
          response: ctx.response,
        }
      },
    })


     /**
     * 获取项目database信息
     */
     const {
      isFetching: loadingWithGetDatabaseDatas,
      execute: fetchGetDatabaseDatas,
    } = useCustomFetch<IDatabase[]>('/engine-service/api/v1/database/list', {
      initialData: [],
      immediate: false,
      afterFetch(ctx: AfterFetchContext<IBasic<IDatabase[]>>) {
        if (ctx.data && ctx.data.code === 0) {
          config.databaseDatas = ctx.data.data
          config.databaseListDataProxy = ctx.data.data.map((item) =>
            objectPick(item, ['id', 'domain', 'driver', 'port', 'databaseName', 'databaseType', 'userName', 'password', 'description']),
          )
          modifyConfig({ databaseId: ctx.data.data[0].id })

          return {
            data: ctx.data.data,
            response: ctx.response,
          }
        }
        return {
          data: [],
          response: ctx.response,
        }
      },
    })


    /**
     * 获取项目proxy信息
     */
     const {
      isFetching: loadingWithGetProxyDatas,
      execute: fetchGetProxyDatas,
    } = useCustomFetch<IProxy[]>('/engine-service/api/v1/proxy/find', {
      initialData: [],
      immediate: false,
      afterFetch(ctx: AfterFetchContext<IBasic<IProxy[]>>) {
        if (ctx.data && ctx.data.code === 0) {
          config.proxyDatas = ctx.data.data
          config.proxyListDataProxy = ctx.data.data.map((item) =>
            objectPick(item, ['id', 'name', 'domain',  'port', 'protocol', 'description']),
          )
          modifyConfig({ proxyId: ctx.data.data[0].id })

          return {
            data: ctx.data.data,
            response: ctx.response,
          }
        }
        return {
          data: [],
          response: ctx.response,
        }
      },
    })


    function modifyConfig(_config: Partial<typeof config>) {
      console.info("存的id都有：" + JSON.stringify(_config))
      // @ts-expect-error
      Object.entries(_config).forEach(([key, value]) => (config[key] = value))

    }

    let selectedStep:any = ref('');

    function setSelectedStep(step: any) {
      selectedStep.value = step
    }

    let testType = ref('API');

    function setTestType(type:string){
      testType.value = type;
    }


    // 步骤页面是点击的添加new，还是编辑edit，
    let controlStepState = ref('default')
    // 设置步骤页面是点击的添加new，还是编辑edit，
    function setControlStepState(type: string){
      controlStepState.value = type
    }

    // 设置主题模式 默认-黑暗模式
    let openLight = ref(false)
    function setOpenLight(type: boolean){
      openLight.value = type
      console.log('setOpenLight-->type', type)
      console.log('setOpenLight-->', openLight.value)
    }
  
    return {
      loginToken,
      isLogin,
      config,
      modifyConfig,
      setLoginToken,
      fetchGetProjectDatas,
      fetchGetEnvironmentDatas,
      fetchGetDatabaseDatas,
      fetchGetProxyDatas,
      loadingWithGetProjectDatas,
      loadingWithGetEnvironmentDatas,
      loadingWithGetDatabaseDatas,
      loadingWithGetProxyDatas,
      selectedStep,
      setSelectedStep,
      testType,
      setTestType,
      controlStepState,
      setControlStepState,
      openLight,
      setOpenLight
    }
  },
  {
    persist: true,
  },
)
